package com.feiyu.util;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.*;
import java.util.Properties;

/**
 * @author nanshouxiao@teacher.com.cn
 * @date 2018-08-27 11:06
 */
public class MybatisUtils {
    private static Properties prop = new Properties();

    private static final String CONFIG_FILE = "config.properties";

    private static final String PROJECT_PATH = jdbcUtils.class.getResource("/").getPath();

    private static String DRIVER;

    private static String URL;

    private static String USERNAME;

    private static String PASSWORD;

    static
    {
        loadPropertiesFile();
    }

    private static void loadPropertiesFile()
    {
        try
        {

            prop.load(new FileReader(PROJECT_PATH + CONFIG_FILE));
            DRIVER = prop.getProperty("jdbc_driver");
            URL = prop.getProperty("jdbc_url");
            USERNAME = prop.getProperty("jdbc_user");
            PASSWORD = prop.getProperty("jdbc_password");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSqlSessionFactory() {
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, getResource());
        Configuration config = new Configuration(environment);
        config.addMappers("com.feiyu.mapper");
        setResource(config, "mapper/CommonMapper.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
        return sqlSessionFactory;
    }

    private static void setResource(Configuration configuration, String resource){
        try (InputStream inputStream = Resources.getResourceAsStream(resource);){
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static DataSource getResource(){
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        return dataSource;
    }
}
